--- 模块功能：新设备发送HTTP请求获取clientNo.
-- @author zhangfenghe
-- @module Tweeter.getNewClientNo
-- @license MIT
-- @copyright openLuat
-- @release 2022.04.26
module(..., package.seeall)

require "http"
require "nvm"
require "mqttTask"
require "mqttTaskQuakeInfoRel"
require "registerTask"
require "utilsBySelf"
require "rtos"
require "logGenerator"
require "thirdPartyHttpRequest"
require "mqttTaskThird"

-- 初始化nvm获取配置参数
nvm.init("config.lua", true)
local logInfo, errInfo, sysTime = "", "", ""
local strLen = string.len
local clientNo, ip, license, owner, type, groupId, clientId, uname, pwd, scope,
      mqtthost, topic, eqrTopic, answerTopic, port, regCenter, isOpenProject,
      mqttHostThird, mqttPortThird, groupIdThird, clientIdThird, unameThird,
      pwdThird, merchantNo, ipCenter, scenarioId, longitude, latitude =
    nvm.get("info")[1], nvm.get("centerConfig")[1], nvm.get("centerConfig")[2],
    nvm.get("centerConfig")[3], nvm.get("centerConfig")[4],
    nvm.get("centerConfig")[5], nvm.get("centerConfig")[6],
    nvm.get("centerConfig")[7], nvm.get("centerConfig")[8],
    nvm.get("centerConfig")[9], nvm.get("centerConfig")[10],
    nvm.get("centerConfig")[11], nvm.get("centerConfig")[12],
    nvm.get("centerConfig")[13], nvm.get("centerConfig")[14],
    nvm.get("regCenter"), nvm.get("isOpenProject"), nvm.get("thirdConfig")[1],
    nvm.get("thirdConfig")[2], nvm.get("thirdConfig")[3],
    nvm.get("thirdConfig")[4], nvm.get("thirdConfig")[5],
    nvm.get("thirdConfig")[6], nvm.get("thirdConfig")[12],
    nvm.get("thirdConfig")[11], nvm.get("thirdConfig")[13],
    nvm.get("longitude"), nvm.get("latitude")
-- 外接mqtt服务器连接任务
local function mqttTaskThirdAsk() mqttTaskThird.startMQTTClientThird() end
-- 第三方平台信息注册，登陆任务
local function thirdPartyPlatformTask()
    if isOpenProject == "true" then
        if mqttHostThird == "" or mqttPortThird == "" or clientIdThird == "" or
            unameThird == "" or pwdThird == "" or groupIdThird == "" then
            local params = {
                merchantNo = merchantNo,
                serialNumber = clientNo,
                scenarioId = scenarioId,
                longitude = longitude,
                latitude = latitude
            }
            thirdPartyHttpRequest.RegistrationAndChange(params)
        else
            sys.taskInit(mqttTaskThirdAsk)
        end
    end

end
local function autoRegister()
    log.info("自动注册任务！！")
    log.info("regCenter", regCenter, "clientId", clientId)
    if regCenter == true then
        if clientId == nil or clientId == "" then
            if strLen(ip) > 0 and strLen(license) > 0 and strLen(owner) > 0 and
                strLen(type) > 0 then
                log.info("注册第二部",
                         "ip" ~= ip and "license" ~= license and "owner" ~=
                             owner and "type" ~= type)
                if "ip" ~= ip and "license" ~= license and "owner" ~= owner and
                    "type" ~= type then
                    log.info("自动注册请求")
                    registerTask.RegistrationServiceTask()
                end
            end
        elseif strLen(clientId) > 0 and strLen(groupId) > 0 and strLen(uname) >
            0 and strLen(pwd) > 0 then
            if (answerTopic == nil or answerTopic == "") and strLen(scope) > 0 then
                registerTask.AuthorizationApplicationUpdateServiceTask()
            end
        end
    end
end
-- 外接mqtt服务器连接任务
local function mqttTaskQuakeInfoRelAsk()
    mqttTaskQuakeInfoRel.startMQTTClient(clientNo)
end
-- 本司mqtt服务器连接任务
local function mqttTaskAsk() mqttTask.startMQTTClient(clientNo) end
local function cbFnc(result, prompt, head, body)
    log.info("getNewClientNo.cbFnc", result, prompt)
    if result and head then
        for k, v in pairs(head) do
            log.info("getNewClientNo.cbFnc", k .. ": " .. v)
            sysTime = utilsBySelf.GetSystemTime()
            logInfo = logInfo .. "[" .. sysTime .. "]" ..
                          "[getNewClientNo.cbFnc:]" .. k .. ": " .. v .. "\n"
        end
    else
        sysTime = utilsBySelf.GetSystemTime()
        errInfo = errInfo .. "[" .. sysTime .. "]" ..
                      "[获取新设备号请求头错误！]\n"
    end
    if result and body then
        log.info("getNewClientNo.cbFnc", "bodyLen=" .. body:len())
        log.info("body", body)
        clientNo = body
        for i = 1, 10 do log.info("[clientNo:]" .. clientNo .. "\n") end
        sysTime = utilsBySelf.GetSystemTime()
        logInfo =
            logInfo .. "[" .. sysTime .. "]" .. "[getNewClientNo.cbFnc:]" ..
                "bodyLen=" .. body:len() .. ",body=" .. body .. "\n"
        nvm.sett("info", 1, clientNo, "SVR")
        sys.restart("新设备编号存储，设备重启生效！！！")
    else
        sysTime = utilsBySelf.GetSystemTime()
        errInfo = errInfo .. "[" .. sysTime .. "]" ..
                      "[获取新设备号请求体错误！]\n"
        logGenerator.generateLogTask(errInfo, "log")
    end
    log.info("getAndSetClientNo")
end
-- 获取并设置设备号
local function getAndSetClientNo()
    if "true" == regCenter then
        regCenter = true
    else
        regCenter = false
    end
    logInfo = ""
    sysTime = string.format("%04d-%02d-%02d %02d:%02d:%02d", os.date("*t").year,
                            os.date("*t").month, os.date("*t").day,
                            os.date("*t").hour, os.date("*t").min,
                            os.date("*t").sec)
    if clientNo == "KS000807" or clientNo == nil then
        http.request("GET", "http://47.94.80.3:8080/quake/register?clientNo=",
                     nil, nil, nil, nil, cbFnc)
    else
        -- nvm.restore()
        sys.taskInit(mqttTaskAsk)
        sys.taskInit(autoRegister)
        --[[ if isOpenProject == "true" then
            utilsBySelf.GetServerObjectByClientNo(clientNo)
        end ]]
        sys.taskInit(thirdPartyPlatformTask)
        if regCenter then
            log.info("登陆外系统条件：", uname ~= nil and pwd ~= nil and
                         mqtthost ~= nil and port ~= nil)
            if uname ~= nil and pwd ~= nil and mqtthost ~= nil and port ~= nil then
                sys.taskInit(mqttTaskQuakeInfoRelAsk)
            end
        end
    end
    logGenerator.generateLogTask(logInfo, "log")
end

getAndSetClientNo()
